//
//  LimitInputText.swift
//  Swift-30-demo
//
//  Created by apple on 2021/11/24.
//

import UIKit

class LimitInputText: UIViewController, UITextViewDelegate {
    let limitedTextView = UITextView()
    let allowInputNumberLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "Limit Input Text"
        self.view.backgroundColor = UIColor(hexStr: "#F5F5F7")
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(note:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        let bgView = UIView()
        bgView.backgroundColor = UIColor.white
        self.view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.top.equalTo(navgationHeight)
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.height.equalTo(140)
        }
        
        limitedTextView.font = UIFont.systemFont(ofSize: 14)
        limitedTextView.delegate = self
        bgView.addSubview(limitedTextView)
        limitedTextView.snp.makeConstraints { make in
            make.top.equalTo(bgView)
            make.leading.equalTo(bgView).offset(20)
            make.trailing.equalTo(bgView).offset(-20)
            make.bottom.equalTo(bgView)
        }
        
        allowInputNumberLabel.textAlignment = .right
        allowInputNumberLabel.text = "0/30"
        bgView.addSubview(allowInputNumberLabel)
        allowInputNumberLabel.snp.makeConstraints { make in
            make.trailing.equalTo(-15)
            make.bottom.equalTo(-15)
        }
    }
    
    func textViewDidChange(_ textView: UITextView) {
        let currentCharactorCount = (textView.text?.count)!
        if  currentCharactorCount >= 30 {
            limitedTextView.resignFirstResponder()
        }
        allowInputNumberLabel.text = "\(currentCharactorCount)/30"
    }
    
    @objc func keyboardWillChangeFrame(note: Notification) {
        let duration = note.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        let endFrame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        //计算工具栏距离底部的间距
        let margin = UIScreen.main.bounds.height - y
        UIView.animate(withDuration: duration) {
            if margin > 0 {
                // 键盘弹出
                print("弹出键盘，键盘高度为：\(margin)")
            }else {
                // 键盘收起
                print("键盘落下！！！！！！")
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

}
